# Copyright (c) OpenMMLab. All rights reserved.
from .builder import DATASETS
from .custom import CustomDataset
import numpy as np

@DATASETS.register_module()
class ISAIDDataset(CustomDataset):
    """ dataset.

    In segmentation map annotation for Potsdam dataset, 0 is the ignore index.
    ``reduce_zero_label`` should be set to True. The ``img_suffix`` and
    ``seg_map_suffix`` are both fixed to '.png'.
    """
    CLASSES = ('ship', 'storage tank', 'basebell diamond', 'tennis court', 'basketball court',
               'ground track field', 'bridge', 'large vehicle', 'small vehicle', 'helicopter', 'swimming pool'
               , 'roundabout', 'soccer ball field', 'plane', 'harbor')

    PALETTE = [[0, 0, 63], [0, 63, 63], [0, 63, 0], [0, 63, 127], [0, 63, 191]
               , [0, 63, 255], [0, 127, 63], [0, 127, 127], [0, 0, 127], [0, 0, 191]
               , [0, 0, 255], [0, 191, 127], [0, 127, 191], [0, 127, 255], [0, 100, 155]]
    
    # def __init__(self, **kwargs):
    #     super(PotsdamDataset, self).__init__(
    #         img_suffix='.png',
    #         seg_map_suffix='.png',
    #         reduce_zero_label=True,
    #         **kwargs)
    def __init__(self,
                 crop_pseudo_margins=None,
                 img_suffix='.png',
                 seg_map_suffix='.png',
                 **kwargs):
        if crop_pseudo_margins is not None:
            assert kwargs['pipeline'][-1]['type'] == 'Collect'
            kwargs['pipeline'][-1]['keys'].append('valid_pseudo_mask')
        super(ISAIDDataset, self).__init__(
            img_suffix=img_suffix, seg_map_suffix=seg_map_suffix, **kwargs)
                
        self.pseudo_margins = crop_pseudo_margins
        self.valid_mask_size = [1024, 2048]
        
    
    def pre_pipeline(self, results):
        super(ISAIDDataset, self).pre_pipeline(results)
        if self.pseudo_margins is not None:
            results['valid_pseudo_mask'] = np.ones(
                self.valid_mask_size, dtype=np.uint8)
            # Don't trust pseudo-labels in regions with potential
            # rectification artifacts. This can lead to a pseudo-label
            # drift from sky towards building or traffic light.
            if self.pseudo_margins[0] > 0:
                results['valid_pseudo_mask'][:self.pseudo_margins[0], :] = 0
            # Here, the if statement is absolutely necessary
            if self.pseudo_margins[1] > 0:
                results['valid_pseudo_mask'][-self.pseudo_margins[1]:, :] = 0
            if self.pseudo_margins[2] > 0:
                results['valid_pseudo_mask'][:, :self.pseudo_margins[2]] = 0
            # Here, the if statement is absolutely necessary
            if self.pseudo_margins[3] > 0:
                results['valid_pseudo_mask'][:, -self.pseudo_margins[3]:] = 0
            results['seg_fields'].append('valid_pseudo_mask')